<template>
  <div class="app-container">
    <el-form ref="queryRole" :model="formRole" :inline="true" size="small">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formRole.roleName" placeholder="角色名称" />
      </el-form-item>
      <el-form-item label="角色状态" prop="status">
        <el-select v-model="formRole.status" placeholder="角色状态">
          <el-option
            v-for="(item,index) in dict.dict.switch"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryRoleInfo()">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetInfo('queryRole')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="it1">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="saveRoleInfo()"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table
      :data="roleTable"
      tooltip-effect="dark"
      :stripe="true"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="角色编号" type="index" width="120" />
      <el-table-column prop="roleName" label="角色名称" width="120" />
      <el-table-column prop="createBy" label="创建者" width="120" />
      <el-table-column key="status" prop="status" label="角色状态" width="140">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :disabled="scope.row.id === '68f7d27c5b8311ed81ea525400cfb560' ? true : false"
            :active-value="0"
            :inactive-value="1"
            @change="switchStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150" show-overflow-tooltip />
      <el-table-column prop="updateTime" label="更新时间" width="150" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{ row.updateTime || '暂无修改' }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        min-width="250"
        align="center"
      >
        <template v-if="scope.row.id !== '68f7d27c5b8311ed81ea525400cfb560'" slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            icon="el-icon-edit"
            @click="updateRoleInfo(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-key"
          >重置</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteRoleInfo(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="formRole.pageIndex"
      :limit.sync="formRole.pageSize"
      @pagination="queryRoleInfo"
    />

    <el-dialog :title="title" :visible.sync="dialogTableVisible" width="500px" :close-on-click-modal="false">
      <el-form ref="diagForm" :model="diagFormRole" :rules="rules" size="small" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="diagFormRole.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="diagFormRole.status">
            <el-radio
              v-for="dict in dict.dict.switch"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="tree"
            class="tree-border"
            :data="menuData"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDefine()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { pageRoleInfo, updateRoleStatus, insertOrUpdateRole, deleteRole, getRoleInfo } from '@/api/system/role'
import { treeMenuList, getMenulistByRoleId as menulistByRoleId } from '@/api/system/menu'
export default ({
  name: 'Role',
  dicts: ['switch'],
  data() {
    return {
      rules: {
        roleName: [
          { required: true, message: '角色名不能为空', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在1到5个字符' }
        ]
      },
      // 搜索参数
      formRole: {
        roleName: '',
        status: '',
        pageIndex: 1,
        pageSize: 10
      },
      // 表格数据
      roleTable: [],
      // 总条数
      total: 0,
      dialogTableVisible: false,
      title: '',
      diagFormRole: {},
      // 菜单权限数据
      menuData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 新增 or 修改
      insertOrupdate: false
    }
  },
  created() {
    this.queryRoleInfo()
  },
  methods: {
    // 表格数据
    queryRoleInfo() {
      pageRoleInfo(this.formRole).then(response => {
        this.roleTable = response.data.dataInfo
        this.total = response.data.total
      })
    },
    // 重置信息
    resetInfo(queryForm) {
      this.resetForm(queryForm)
    },
    // 清空表单
    restForms() {
      if (this.$refs.tree !== undefined) {
        this.$refs.tree.setCheckedKeys([])
      }
      this.diagFormRole = {
        roleName: undefined,
        status: 0
      }
      this.resetForm('diagForm')
    },
    // 修改状态
    switchStatus(row) {
      const statusText = row.status === 0 ? '启用 ' : '停用 '
      this.$confirm('确定要' + statusText + row.roleName + ' 角色吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const statusInfo = {}
        statusInfo.status = row.status
        statusInfo.id = row.id
        return updateRoleStatus(statusInfo)
      }).then(() => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
        this.queryRoleInfo()
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0
      })
    },
    // 菜单权限下拉框树列表
    treeMenuList() {
      treeMenuList().then(response => {
        this.menuData = response.data
      })
    },
    // 新增
    saveRoleInfo() {
      this.restForms()
      this.treeMenuList()
      this.title = '新增操作'
      this.dialogTableVisible = true
      this.insertOrupdate = false
    },
    // 获取菜单权限下拉框树列表
    menuCheckkeysAll() {
      const keys = this.$refs.tree.getCheckedKeys()
      const halKeys = this.$refs.tree.getHalfCheckedKeys()
      keys.unshift.apply(keys, halKeys)
      return keys
    },
    /** 根据角色id查询相关菜单 */
    getMenulistByRoleId(roleId) {
      return menulistByRoleId(roleId).then(response => {
        this.menuData = response.data.menuList
        return response
      })
    },

    // 点击修改
    updateRoleInfo(row) {
      this.insertOrupdate = true
      this.restForms()
      const roleInfo = {
        id: row.id
      }
      const menu = this.getMenulistByRoleId(row.id)
      /** 根据角色id 查询角色信息 */
      getRoleInfo(roleInfo).then(response => {
        this.diagFormRole = response.data
        this.dialogTableVisible = true
        this.$nextTick(() => {
          menu.then(res => {
            const checkKeys = res.data.checkKeys
            checkKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.tree.setChecked(v, true, false)
              })
            })
          })
        })
        this.title = '修改操作'
      })
    },
    // 新增 or 修改提交
    submitDefine() {
      this.$refs.diagForm.validate(valid => {
        if (valid) {
          const menuId = this.menuCheckkeysAll()
          this.diagFormRole.menuIdList = menuId
          insertOrUpdateRole(this.diagFormRole).then(() => {
            if (this.insertOrupdate) {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
            } else {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
            }
            this.dialogTableVisible = false
            this.queryRoleInfo()
          })
        } else {
          return false
        }
      })
    },
    // 删除角色信息
    deleteRoleInfo(row) {
      const roleId = row.id
      const params = {
        id: roleId
      }
      this.$confirm('确定要删除' + row.roleName + ' 角色吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(params).then(() => {
          this.$message({
            type: 'info',
            message: '删除成功'
          })
          this.queryRoleInfo()
        })
      }).catch(() => {})
    }
  }
})
</script>
